//
//  RHUserVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2024/11/13.
//

#import "RHUserVC.h"
#import "JXCategoryView.h"
#import "JXCategoryListContainerView.h"
#import "RHSearchView.h"
#import "RHUserListVC.h"
#import "RHUserGroupListVC.h"
#import "RHAddUserVC.h"
#import "RHAddUserGroupVC.h"
#import "RHGolobalSetModel.h"
#import "RHVppGroupSetView.h"

@interface RHUserVC ()<JXCategoryListContainerViewDelegate,JXCategoryViewDelegate,JXCategoryTitleViewDataSource,QMUITextFieldDelegate>

@property (nonatomic, strong) NSMutableArray *titles;

@property (nonatomic, strong) JXCategoryTitleView *categoryView;

@property (nonatomic, strong) JXCategoryListContainerView *listContainerView;

@property (nonatomic, assign) NSInteger idx;

@property (nonatomic, strong) RHSearchView *searchView;

@property (nonatomic, strong) RHGolobalSetModel *vppConfigModel;
@end

@implementation RHUserVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"用户列表".rh_localized];
    [self.view setBackgroundColor:CFTabViewBgColor];
    self.titles = @[@"用户".rh_localized,
                    @"分组".rh_localized].mutableCopy;

    [self setupUI];
}

- (void)setupUI{
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getPlantCount) name:PlantListNeedUpdateNotification object:nil];
    kWeakSelf;
    UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0,40, 64)];
    [addButton setImage:[UIImage imageNamed:@"create_user"] forState:UIControlStateNormal];
    [addButton setBackgroundColor:UIColor.clearColor];
    [addButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [addButton.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [addButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    //[addButton addTarget:self action:@selector(didClickAdd) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarBtn = [[UIBarButtonItem alloc] initWithCustomView:addButton];
    self.navigationItem.rightBarButtonItem = rightBarBtn;

    [[addButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        RHAddUserVC *vc = [[RHAddUserVC alloc] init];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    
    //搜索栏
    _searchView = [[RHSearchView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 55)];
    [self.view addSubview:_searchView];
    _searchView.delegate = self;
    _searchView.searchTextField.placeholder = @"请输入关键字".rh_localized;
    
    _listContainerView = [[JXCategoryListContainerView alloc] initWithType:JXCategoryListContainerType_ScrollView delegate:self];
    [self.view addSubview:self.listContainerView];
    _listContainerView.scrollView.scrollEnabled = NO;
    _categoryView = [[JXCategoryTitleView alloc] initWithFrame:CGRectMake(0,0, [UIScreen mainScreen].bounds.size.width, 50)];
    self.categoryView.titles = self.titles;
    self.categoryView.backgroundColor = [UIColor whiteColor];
    self.categoryView.delegate = self;
    self.categoryView.cellWidth = 60;
    self.categoryView.titleSelectedColor = kCOLOR_HEX(@"405DBE");
    self.categoryView.titleColor = kCOLOR_HEX(@"969799");
    self.categoryView.titleFont = [UIFont systemFontOfSize:14];
    self.categoryView.titleSelectedFont = [UIFont boldSystemFontOfSize:14];
    self.categoryView.titleColorGradientEnabled = YES;
    self.categoryView.titleLabelZoomEnabled = NO;
    self.categoryView.titleLabelZoomScale = 1.0;
    self.categoryView.cellSpacing = 30;
//    self.categoryView.contentEdgeInsetLeft = 20;
//    self.categoryView.contentEdgeInsetRight = 20;
    self.categoryView.titleLabelVerticalOffset = -10;
    [self.view addSubview:self.categoryView];
    self.categoryView.listContainer = self.listContainerView;
    
    JXCategoryIndicatorBackgroundView *backgroundView = [[JXCategoryIndicatorBackgroundView alloc] init];
     backgroundView.size = CGSizeMake(60, 3);
     backgroundView.indicatorColor = kCOLOR_HEX(@"#405DBE");
     backgroundView.indicatorHeight = 3;
     backgroundView.indicatorWidth = 60;
     backgroundView.verticalMargin = -10;
     backgroundView.indicatorCornerRadius = 1.5;

     _categoryView.indicators = @[backgroundView];
        
    
    
    [_categoryView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(weakSelf.searchView.mas_bottom);
        make.height.mas_equalTo(50);
    }];
    
    [_listContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(self.categoryView.mas_bottom).offset(0);
        make.bottom.mas_offset(0);
    }];
    
}

#pragma mark ----- 获取一键配置
-(void)getplantGroupGolobalConfig{
    [QMUITips showLoadingInView:kAppWindow];
    [RHGolobalSetModel startGetWithCompletionAPIKey:H_getPlantGroupForceConfig argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            self.vppConfigModel = resultModel.data;
            NSMutableArray *mtbArr = [NSMutableArray array];
            if (request.responseJSONObject[@"data"]) {
                RHGolobalSetModel *s40K = [RHGolobalSetModel yy_modelWithJSON:request.responseJSONObject[@"data"][@"S40K LV1.0"]];
                RHGolobalSetModel *me233 = [RHGolobalSetModel yy_modelWithJSON:request.responseJSONObject[@"data"][@"R-SM233120A0-US"]];
                RHGolobalSetModel *me233_K = [RHGolobalSetModel yy_modelWithJSON:request.responseJSONObject[@"data"][@"K-KS233125A0-US"]];
                if (s40K) {
                    [mtbArr addObject:s40K];
                }
                if (me233) {
                    [mtbArr addObject:me233];
                }
                if (me233_K) {
                    [mtbArr addObject:me233_K];
                }
            }
            RHVppGroupSetView *setView = [[RHVppGroupSetView alloc]initWithConfig:mtbArr.copy];
            kWeakSelf;
            setView.configBlock = ^{
//                UIViewController *vc = weakSelf.listContainerView.validListDict[@(1)];
//                if ([vc isKindOfClass:[KWTPlantGroupListVC class]]) {
//                    KWTPlantGroupListVC *groupVC = (KWTPlantGroupListVC*)weakSelf.listContainerView.validListDict[@(1)];
//                    groupVC.configModel = weakSelf.vppConfigModel;
//                }
            };
            [setView show];
        }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
        }];
    
}

-(void)addAction
{
    //添加用户
    if (self.categoryView.selectedIndex == 0) {
        RHUserListVC *vc = [[RHUserListVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        //添加用户分组
        RHAddUserGroupVC *vc = [[RHAddUserGroupVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];

    }
}






#pragma mark - JXCategoryViewDelegate

// 点击选中或者滚动选中都会调用该方法。适用于只关心选中事件，不关心具体是点击还是滚动选中的。
- (void)categoryView:(JXCategoryBaseView *)categoryView didSelectedItemAtIndex:(NSInteger)index {
    NSLog(@"%@", NSStringFromSelector(_cmd));
    // 侧滑手势处理
    self.navigationController.interactivePopGestureRecognizer.enabled = (index == 0);
    if (index == 0) {
        self.navigationItem.title = @"用户列表".rh_localized;
        kWeakSelf;
        
        QMUIButton *addButton = [[QMUIButton alloc] initWithFrame:CGRectMake(0, 0,30, 40)];
        [addButton setImage:[UIImage imageNamed:@"create_user"] forState:UIControlStateNormal];
        [addButton setBackgroundColor:UIColor.clearColor];
        [addButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        [addButton addTarget:self action:@selector(addAction) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightBarBtn = [[UIBarButtonItem alloc] initWithCustomView:addButton];
        self.navigationItem.rightBarButtonItems = @[rightBarBtn];

    }else{
        kWeakSelf;
        self.navigationItem.title = @"用户分组".rh_localized;
        QMUIButton *addButton = [[QMUIButton alloc] initWithFrame:CGRectMake(0, 0,30, 40)];
        [addButton setImage:[UIImage imageNamed:@"kwt_add_plant2"] forState:UIControlStateNormal];
        [addButton setBackgroundColor:UIColor.clearColor];
        [addButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        
        QMUIButton *configButton = [[QMUIButton alloc] initWithFrame:CGRectMake(0, 0,30, 40)];
        [configButton setImage:[UIImage imageNamed:@"plant_chg_config2"] forState:UIControlStateNormal];
        [configButton setBackgroundColor:UIColor.clearColor];
        [configButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        
        UIBarButtonItem *rightBarBtn1 = [[UIBarButtonItem alloc] initWithCustomView:addButton];
        UIBarButtonItem *rightBarBtn2 = [[UIBarButtonItem alloc] initWithCustomView:configButton];
       
       
        [[addButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [weakSelf addAction];
        }];
        
        [[configButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [weakSelf getplantGroupGolobalConfig];
        }];
        self.navigationItem.rightBarButtonItems = @[rightBarBtn2,rightBarBtn1];

    }
}

// 滚动选中的情况才会调用该方法
- (void)categoryView:(JXCategoryBaseView *)categoryView didScrollSelectedItemAtIndex:(NSInteger)index {
    NSLog(@"%@", NSStringFromSelector(_cmd));
}

#pragma mark - JXCategoryListContainerViewDelegate
// 返回列表的数量
- (NSInteger)numberOfListsInlistContainerView:(JXCategoryListContainerView *)listContainerView {
    return  self.titles.count;
}

// 返回各个列表菜单下的实例，该实例需要遵守并实现 <JXCategoryListContentViewDelegate> 协议
- (id<JXCategoryListContentViewDelegate>)listContainerView:(JXCategoryListContainerView *)listContainerView initListForIndex:(NSInteger)index {
    if (index == 0) {
        RHUserListVC *vc = [[RHUserListVC alloc] init];
        vc.isHideSearchView = YES;
//        vc.index = index;
//        kWeakSelf;
//        //刷新
//        vc.refreshBlock = ^() {
//            weakSelf.searchView.searchTextField.text = nil;
//    //        [weakSelf getPlantCount];
//        };
        
        return vc;
    }else{
        return [[RHUserGroupListVC alloc]init];
    }
    
}




#pragma mark ------- textField delegate
-(void)textFieldDidEndEditing:(UITextField *)textField{
    if ([self.listContainerView.validListDict[@(self.categoryView.selectedIndex)] isKindOfClass:[RHUserListVC class]]) {
        RHUserListVC *listVC = (RHUserListVC*)self.listContainerView.validListDict[@(self.categoryView.selectedIndex)];
        [listVC searchUserListWithKey:textField.text];
    }
    if ([self.listContainerView.validListDict[@(self.categoryView.selectedIndex)] isKindOfClass:[RHUserGroupListVC class]]) {
        RHUserGroupListVC *listVC = (RHUserGroupListVC*)self.listContainerView.validListDict[@(self.categoryView.selectedIndex)];
        [listVC searchGroupListWithKeyCode:textField.text];
    }
}


- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    if ([self.listContainerView.validListDict[@(self.categoryView.selectedIndex)] isKindOfClass:[RHUserListVC class]]) {
        RHUserListVC *listVC = (RHUserListVC*)self.listContainerView.validListDict[@(self.categoryView.selectedIndex)];
        [listVC searchUserListWithKey:@""];
    }
    if ([self.listContainerView.validListDict[@(self.categoryView.selectedIndex)] isKindOfClass:[RHUserGroupListVC class]]) {
        RHUserGroupListVC *listVC = (RHUserGroupListVC*)self.listContainerView.validListDict[@(self.categoryView.selectedIndex)];
        [listVC searchGroupListWithKeyCode:@""];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.searchView resignFirstResponder];
    });
    return YES;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


@end
